package com.scujj.cs6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.cs6.common.BusinessException;
import com.scujj.cs6.common.ErrorCode;
import com.scujj.cs6.config.JwtProperties;
import com.scujj.cs6.mapper.UserMapper;
import com.scujj.cs6.model.dto.user.UserEmailLoginDTO;
import com.scujj.cs6.model.dto.user.UserInfoUpdateDTO;
import com.scujj.cs6.model.dto.user.UserPhoneLoginDTO;
import com.scujj.cs6.model.dto.user.UserRegisterDTO;
import com.scujj.cs6.model.entity.User;
import com.scujj.cs6.model.vo.UserSimpleVo;
import com.scujj.cs6.model.vo.UserVo;
import com.scujj.cs6.service.UserService;
import com.scujj.cs6.utils.JwtTool;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author FlanChan
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-03-25 21:21:24
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private final JwtTool jwtTool;

    private final JwtProperties jwtProperties;

    @Override
    public UserVo getUserDetailByToken(HttpServletRequest request) {
        return this.baseMapper.selectUserDetailById((Long) request.getAttribute("user"));
    }

    @Override
    public UserVo getUserDetailById(Long id) {
        return this.baseMapper.selectUserDetailById(id);
    }

    @Override
    public UserSimpleVo getUserByToken(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        User user = this.getById(userId);
        if (user == null) {
            return null;
        }
        return new UserSimpleVo(user);
    }

    @Override
    public UserSimpleVo getUserById(Long id) {
        User user = this.getById(id);
        if (user == null) {
            throw new RuntimeException("User not found");
        }
        return new UserSimpleVo(user);
    }

    @Override
    public void emailLogin(UserEmailLoginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) {
        User user = this.getOne(new LambdaQueryWrapper<>(User.class)
                .eq(User::getEmail, loginDTO.getEmail()));
        if (user == null || !user.getPassword().equals(loginDTO.getPassword())) {
            throw new RuntimeException("Invalid email or password");
        }
        String token = jwtTool.createToken(user.getId(), jwtProperties.getTokenTTL());
        response.setHeader("Authorization", token);
    }

    @Override
    public void phoneLogin(UserPhoneLoginDTO loginDTO, HttpServletRequest request, HttpServletResponse response) {
        User user = this.getOne(new LambdaQueryWrapper<User>(User.class).eq(User::getPhone, loginDTO.getPhone()));
        if (user == null || !user.getPassword().equals(loginDTO.getPassword())) {
            throw new RuntimeException("Invalid phone number or password");
        }
        String token = jwtTool.createToken(user.getId(), jwtProperties.getTokenTTL());
        response.setHeader("Authorization", token);
    }

    @Override
    public void createUser(UserRegisterDTO registerDTO) {
        if (this.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getEmail, registerDTO.getEmail())) != null) {
            throw new RuntimeException("Email already exists");
        }
        if (this.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getPhone, registerDTO.getPhone())) != null) {
            throw new RuntimeException("Phone number already exists");
        }
        User user = new User(registerDTO);
        this.save(user);
    }

    @Override
    public void updateUser(UserInfoUpdateDTO userInfoUpdateDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        User user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("User not found");
        }
        if (!user.getEmail().equals(userInfoUpdateDTO.getEmail())) {
            if (this.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getEmail, userInfoUpdateDTO.getEmail())) != null) {
                throw new RuntimeException("Email already exists");
            }
        }
        if (!user.getPhone().equals(userInfoUpdateDTO.getPhone())) {
            if (this.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getPhone, userInfoUpdateDTO.getPhone())) != null) {
                throw new RuntimeException("Phone number already exists");
            }
            user.setPhone(userInfoUpdateDTO.getPhone());
        }
        if (!userInfoUpdateDTO.getUsername().equals(user.getUsername())) {
            user.setUsername(userInfoUpdateDTO.getUsername());
            this.updateById(user);
        }
    }

    @Override
    public String updateUserAvatar(Long userId, String url) {
        User user = this.getById(userId);
        int i = user.getAvatar().lastIndexOf("user_avatar");
        String OldAvatar = i == -1 ? null : "/" + user.getAvatar().substring(i);
        user.setAvatar(url);
        this.updateById(user);
        return OldAvatar;

    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Authorization", "");
    }

}




